package face.pay.task.order.api;

import com.face.pay.WxApiConfig;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.dao.EnterpriseInfoDao;
import face.pay.dao.OemInfoDao;
import face.pay.dao.OrderInfoDao;
import face.pay.dao.StoreInfoDao;
import face.pay.entity.EnterpriseInfo;
import face.pay.entity.OemInfo;
import face.pay.entity.OrderInfo;
import face.pay.task.order.message.MessageSender;
import face.pay.util.bean.JavaBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: zkj
 * @Date: 2019/9/11 14:08
 * @Description:
 */
@Slf4j
@Component
public class ApiWxPayQuery extends AbstractApi {

    private static final String domain = "api.mch.weixin.qq.com";

    private static final String urlSuffix = "/pay/orderquery";

    @Autowired
    private OrderInfoDao orderInfoDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private StoreInfoDao storeInfoDao;

    @Autowired
    private EnterpriseInfoDao enterpriseInfoDao;


    @Async
    public void orderStatusCheck(OrderInfo orderInfo, WxApiConfig wxApiConfig) {

        Long orderId = orderInfo.getId();
        log.info(">>>>>>开始检测微信订单支付结果:" + orderId);

        Map param = new HashMap();

        Integer oemId = orderInfo.getOemId();

        EnterpriseInfo enterpriseInfo = this.enterpriseInfoDao.queryByUserId(orderInfo.getUserId());

        String appId = wxApiConfig.getAppID();
        String apiKey = wxApiConfig.getKey();
        String mchId = wxApiConfig.getMchID();

        String openId = orderInfo.getPayUserSign();
        String trade_no =orderInfo.getTradeNo();

        String subMchId = enterpriseInfo.getWxSubMchId();

        param.put("appid",appId);
        param.put("mch_id",mchId);
        param.put("sub_mch_id",subMchId);
        param.put("out_trade_no",String.valueOf(orderId));

        String nonce_str = WXPayUtil.generateNonceStr();
        param.put("nonce_str",nonce_str);


        try {
            String xml = WXPayUtil.generateSignedXml(param, apiKey);
            log.info("扫码支付查询>>>>>推送到微信服务器消息xml" + xml);

                WXPayRequest wxPayRequest = new WXPayRequest(wxApiConfig);

                String result = wxPayRequest.requestOnce(domain, urlSuffix, xml, false);
                log.info("扫码支付订单查询<<<<<<返回结果 " + result);
                Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
                if (WXPayUtil.isSuccess(resultMap)) {
                    //查询成功  取出交易状态
                    String trade_state = resultMap.get("trade_state");
                    //订单描述信息
                    String message = resultMap.get("trade_state_desc");

                    /**
                     *1支付成功(SUCCESS)
                     * -5 转入退款(REFUND)
                     * 0未支付(NOTPAY USERPAYING)
                     * -4关闭(CLOSED)
                     * -3取消(REVOKED)
                     * -1支付失败(PAYERROR)
                     * -2下单失败(ERROR)
                     */
                    switch (trade_state) {
                        case "SUCCESS": {
                            //1支付成功(SUCCESS)
                            if(StringUtils.isBlank(openId)){
                                openId =resultMap.get("openid");
                            }
                            if(StringUtils.isBlank(trade_no)){
                                trade_no =resultMap.get("transaction_id");

                            }
                            updateOrderStatus( orderId,openId, trade_no,1, message);

                            /**
                             * 发送分润通知
                             */
                            orderInfo.setStatus(1);
                            orderInfo.setMessage("支付成功");

                            this.sendAllMessage(orderInfo,wxApiConfig.getOemType());
                            break;
                        }
                        //-5 转入退款(REFUND)
                        case "REFUND": {
                            updateOrderStatus(orderId,null,null, -5, message);
                            break;
                        }
                        //0未支付(NOTPAY未支付 USERPAYING支付中)
                        case "USERPAYING": {
                            // updateOrderStatus(orderId,0,message);
                            break;
                        }
                       /* case "NOTPAY": {
                            //updateOrderStatus(orderId,0,message);
                            break;
                        }*/
                        //-3取消(REVOKED)
                        case "REVOKED": {
                            updateOrderStatus(orderId,null,null, -3, message);
                            break;
                        }
                        //-4关闭(CLOSED)
                        case "CLOSED": {
                            updateOrderStatus(orderId,null,null, -4, message);
                            break;
                        }
                        //-1支付失败(PAYERROR)
                        case "PAYERROR": {
                            updateOrderStatus(orderId, null,null,-1, message);
                            break;
                        }
                        //-2下单失败(ERROR)
                        case "ERROR": {
                            updateOrderStatus(orderId,null, null,-2, message);
                            break;
                        }

                    }
                    log.info("<<<<<<<检测微信支付结束结束:" + orderId);
                }


        } catch (Exception e) {
            log.info("微信扫码支付订单查询异常" + e);
        }


    }


    /**
     * 更新订单状态和信息
     */
    private void updateOrderStatus(Long orderId,String openId,String trade_no, Integer status, String message) {
        OrderInfo record = new OrderInfo();
        record.setId(orderId);
        record.setStatus(status);
        record.setPayUserSign(openId);
        record.setProfitSign(0);
        record.setTradeNo(trade_no);
        record.setMessage(message);
        this.orderInfoDao.updatePayInfo(record);
    }
}
